//
//  BatchReceiveViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/6.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "BatchReceiveViewController.h"
#import "SingleScanViewController.h"
#import "SocketRequest.h"
#import "Singleton.h"
#import "BatchExpress.h"
#import "BatchExpressCell.h"

@interface BatchReceiveViewController ()<SocketRequestDelegate,SingleScanViewControllerDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_expressList;
    NSMutableArray *_selectedExpressList;
    
    NSString *_errorMessage;//取件错误信息展示
    NSMutableArray *_failReceiveList;
    NSArray *_showExpressList;
    BOOL _isUploadExpress;
}

@end

@implementation BatchReceiveViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"待取上门件";
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        _expressList = [NSMutableArray arrayWithCapacity:1];
        _selectedExpressList = [NSMutableArray arrayWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _customSearch = [[CustomSearchView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
    _customSearch.delegate = self;
//    self.tableView.tableHeaderView = _customSearch;
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 48)];
    footerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footerView;
    [self getBatchReceiveExpressSocket];
    [self handelNetWorkMethod];
}

- (void)reloadBackButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 30, 22);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button setTitleColor:OrangeColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button addTarget:self action:@selector(backLastViewController) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

//获取批量签收的快件
- (void)getBatchReceiveExpressSocket {
    if (_expressList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        [self.tableView makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STRA"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//批量签收
- (void)sureReceiveExpressSocketWithInwayExpressId:(NSString *)inwayExpressId {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS6"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.userId] length:64];
    NSString *content = [NSString stringWithFormat:@"3,%@,3",inwayExpressId];
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    [mutableData appendData:[SocketMethod hexDataWithLength:contentData.length]];
    [mutableData appendData:contentData];
    [_socketRequest addMultipleSocketData:mutableData SocketTag:2];
}

#pragma mark CustomSearchViewDelegate
- (void)cancelSearch {
    _customSearch.isShowCancel = NO;
    _customSearch.searchTextField.text = @"";
    _showExpressList = _expressList;
    [self reloadTableView];
}

- (void)startScanning {
    SingleScanViewController *scanVC = [[SingleScanViewController alloc] initWithNibName:@"SingleScanViewController" bundle:nil];
    scanVC.delegate = self;
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)startSearchText:(NSString *)text {
    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
    for (BatchExpress *express in _expressList) {
        NSRange range1 = [express.expressId rangeOfString:text];
        NSRange range2 = [express.expressCompanyName rangeOfString:text];
        NSRange range3 = [express.telephone rangeOfString:text];
        if (range1.location != NSNotFound) {
            [mutableArray addObject:express];
        } else if (range2.location != NSNotFound) {
            [mutableArray addObject:express];
        } else if (range3.location != NSNotFound) {
            [mutableArray addObject:express];
        }
    }
    _showExpressList = mutableArray;
    [self reloadTableView];
}

- (void)reloadTableView {
    [self.tableView reloadData];
    if (_showExpressList.count > 0) {
        [self.tableView makeNone];
    } else {
        [self.tableView makeTip:@"无待取上门件"];
    }
}

#pragma mark SingleScanViewControllerDelegate
- (void)didFinishSingleScanningCode:(NSString *)code {
    _customSearch.searchTextField.text = code;
    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:1];
    for (BatchExpress *express in _expressList) {
        if ([express.expressId isEqualToString:code]) {
            [mutableArray addObject:express];
        }
    }
    _showExpressList = mutableArray;
    [self reloadTableView];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _showExpressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == (_showExpressList.count - 1)) {
        return 200;
    }
    return 206;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return _customSearch;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"BatchExpressCell";
    BatchExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"BatchExpressCell" owner:self options:nil] lastObject];
    }
    BatchExpress *express = [_showExpressList objectAtIndex:indexPath.row];
    if ([_selectedExpressList containsObject:express]) {
        [cell reloadBatchExpressCell:express Selected:YES];
    } else {
        [cell reloadBatchExpressCell:express Selected:NO];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BatchExpress *express = [_showExpressList objectAtIndex:indexPath.row];
    if ([_selectedExpressList containsObject:express]) {
        [_selectedExpressList removeObject:express];
    } else {
        [_selectedExpressList addObject:express];
    }
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self reloadBottom];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    BatchExpress *express = [[BatchExpress alloc] initWithString:string];
                    [_expressList addObject:express];
                }
            }
            if (_expressList.count <= 0) {
                [self.tableView makeTip:@"无待取上门件"];
                _bottomView.hidden = YES;
                _customSearch.hidden = YES;
            } else {
                _bottomView.hidden = NO;
                self.tableView.backgroundView = nil;
                _showExpressList = _expressList;
                [_selectedExpressList addObjectsFromArray:_expressList];
                _bottomView.hidden = NO;
                if (_expressList.count > 0) {
                    self.title = [NSString stringWithFormat:@"待取上门件(%ld)",(long)_expressList.count];
                } else {
                    self.title = @"待取上门件";
                }
                [self reloadBottom];
            }
            [self.tableView reloadData];
        } else {
            [self.tableView makeTip:msg];
        }
    } else if (socket.socketTag == 2) {
        [ToastActivity dismissInView:self.view];
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            if (content.length > 0) {
                NSArray *array = [content componentsSeparatedByString:@"|"];
                for (NSString *string in array) {
                    if (string.length > 0) {
                        NSArray *sonArray = [string componentsSeparatedByString:@","];
                        NSString *inwayExpressId = [SocketMethod subArray:sonArray Index:0];
                        NSString *error = [SocketMethod subArray:sonArray Index:1];
                        for (BatchExpress *express in _expressList) {
                            if ([inwayExpressId isEqualToString:express.inwayExpressId]) {
                                [_failReceiveList addObject:express];
                                if (_errorMessage) {
                                    _errorMessage = [NSString stringWithFormat:@"%@ %@\n%@",express.expressId,error,_errorMessage];
                                } else {
                                    _errorMessage = [NSString stringWithFormat:@"%@ %@",express.expressId,error];
                                }
                            }
                            
                        }
                    }
                }
            }
        }
        if (_socketRequest.isDisconnectAll) {
            _isUploadExpress = NO;
            [self finishReceive];
        }
    }
}

//签收结束处理
- (void)finishReceive {
    //对数组处理
    NSMutableArray *selectedArray = [NSMutableArray arrayWithArray:_selectedExpressList];
    [selectedArray removeObjectsInArray:_failReceiveList];
    [_expressList removeObjectsInArray:selectedArray];
    [_selectedExpressList removeObjectsInArray:selectedArray];
    if (_expressList.count > 0) {
        self.title = [NSString stringWithFormat:@"待取上门件(%ld)",(long)_expressList.count];
    } else {
        self.title = @"待取上门件";
    }
    //签收结果展示
    if (_failReceiveList.count <= 0) {
        if ([_delegate respondsToSelector:@selector(receiveExpressSuccess)]) {
            [_delegate receiveExpressSuccess];
        }
        [self performSelector:@selector(backLastViewController) withObject:nil afterDelay:1];
    } else {
        [self reloadBottom];
        [self.tableView reloadData];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"签收失败快件" message:_errorMessage delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    if (socket.socketTag == 1) {
        [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getBatchReceiveExpressSocket)];
        [DSToast showText:msg InView:self.view];
    } else {
        _isUploadExpress = NO;
        [ToastActivity dismissInView:self.view];
        if (_socketRequest.isDisconnectAll) {
            [DSToast showText:msg InView:self.view];
        }
    }
}

#pragma mark NibAction
- (IBAction)isSelectedExpress:(id)sender {
    [_selectedExpressList removeAllObjects];
    if (_isSelectedBtn.selected) {
    } else {
        [_selectedExpressList addObjectsFromArray:_expressList];
    }
    [self reloadBottom];
    [self.tableView reloadData];
}

- (void)reloadBottom {
    if (_selectedExpressList.count == _expressList.count) {
        _isSelectedBtn.selected = YES;
    } else {
        _isSelectedBtn.selected = NO;
    }
    NSString *title = [NSString stringWithFormat:@"确认签收（%lu）",(unsigned long)_selectedExpressList.count];
    [_sureReceiveBtn setTitle:title forState:UIControlStateNormal];
}

- (IBAction)sureReceivedSelectedExpress:(id)sender {
    if (_selectedExpressList.count <= 0) {
        [DSToast showText:@"请勾选签收快递" InView:self.view];
    } else if (!_isUploadExpress) {
        _isUploadExpress = YES;
        _errorMessage = nil;
        _failReceiveList = [NSMutableArray arrayWithCapacity:1];
        [ToastActivity makeActivity:@"批量签收中..." InView:self.view];
        for (BatchExpress *express in _selectedExpressList) {
            [self sureReceiveExpressSocketWithInwayExpressId:express.inwayExpressId];
        }
    }
}

- (void)dealloc {
    _socketRequest = nil;
    _expressList = nil;
    _selectedExpressList = nil;
    _failReceiveList = nil;
    _showExpressList = nil;
}

@end
